# 学生信息管理系统 PyCharm
# urls xf
# 2025.07.15 星期二 13:32
# from ___gxf_tool_code import 
# SPT2505

from fastapi import APIRouter
from pydantic import BaseModel
from apps.models import Student

students = APIRouter()


# 获取所有学生信息
@students.get("/msg")
async def get_all_students_msg():
    students = await Student.all().select_related("clas").values(
        "id", "name", "sno", "clas__name"
    )
    return {'status': 200, "msg": "success", "data": students}


@students.get("/msg/{student_id}")
async def get_one_student(student_id):
    student = await Student.filter(id=student_id).select_related("clas").values(
        "id", "name", "sno", "clas__name"
    )
    if student:
        return {"status": 200, "msg": "success", "data": student}
    return {"status": 404, "msg": "Not Found", "data": "没有该学生"}

class StudentModel(BaseModel):
    name:str
    pwd:str
    sno:int
    clas_id:int

@students.post("/add")
async def add_student(stu:StudentModel):
    student = await Student.create(name=stu.name, sno=stu.sno, pwd=stu.pwd, clas_id=stu.clas_id)
    await student.save()
    print(student)
    return {"status": 201, "msg": "success", "data": "成功添加学生信息"}

@students.put("/update/{student_id}")
async def update_student(student_id, stu:StudentModel):
    data = stu.dict(exclude_unset=True)
    await Student.filter(id=student_id).update(**data)
    # print(data)
    return {"status": 200, "msg": "success", "data": "成功更新学生信息"}

@students.delete("/delete/{student_id}")
async def delete_student(student_id):
    await Student.filter(id=student_id).delete()
    return {"status": 200, "msg": "success", "data": "成功删除学生信息"}

